/* eslint-disable strict */
import agconnect from "@hw-agconnect/api"
import "@hw-agconnect/auth"
import "@hw-agconnect/instance"
import { ElMessage } from 'element-plus'
import { userInfoStore } from "../userStore/userStore";
import { UserModel } from "../models/User";
import CryptoJS from 'crypto-js'

const secretKey = "AES";
const iv = CryptoJS.enc.Hex.parse("10000000000000000000000000000001");

// 加密函数
function encryptAES(text: string): string {
    const encrypted = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(secretKey), {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
}

// 解密函数
function decryptAES(cipherText: string): string {
    const decrypted = CryptoJS.AES.decrypt(cipherText, CryptoJS.enc.Utf8.parse(secretKey), {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}
class AgcApis {
    getVerifyCode(phone: string): Promise<boolean> {
        let promise: Promise<boolean> = new Promise<boolean>((resolve, reject) => {
            agconnect.auth().requestPhoneVerifyCode('+86',
                phone,
                agconnect.auth.Action.ACTION_REGISTER_LOGIN,
                'zh_CN',
                60)
                .then((_reslut) => {
                    resolve(true);
                    ElMessage({
                        message: `验证码发送成功，${_reslut.getShortestInterval()}s内有效`,
                        type: 'success',
                    })
                })
                .catch((error) => {
                    reject(error);
                    if (error.ret.code === 203818048) {
                        ElMessage.error('验证码发送时间间隔过短')
                    }
                });
        });
        return promise;
    }

    authByVerifyCode(phone: string, verifyCode: string) {
        const credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('+86', phone, '', verifyCode);
        let result = agconnect.auth().signIn(credential);
        return result;
    }

    authByPassword(phone: string, password: string) {
        const pwdAES: string = encryptAES(password);
        const credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('+86', phone, pwdAES);
        let result = agconnect.auth().signIn(credential);
        return result;
    }

    authByPasswordNoCrypto(phone: string, password: string) {
        const credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('+86', phone, password);
        let result = agconnect.auth().signIn(credential);
        return result;
    }


    registerUser(phone: string, verifyCode: string, password: string): Promise<UserModel> {
        const pwdAES: string = encryptAES(password)
        let phoneUser = new agconnect.auth.PhoneUser('+86', phone, pwdAES, verifyCode);
        let promise: Promise<UserModel> = new Promise((resolve, reject) => {
            agconnect.auth().createPhoneUser(phoneUser)
                .then((user) => {
                    //创建用户成功
                    let newUser: UserModel = {
                        id: user.getUser().getUid(),
                        password: pwdAES,
                        phone: phone,
                        username: ''
                    }
                    resolve(newUser);
                }).catch((error) => {
                    //创建用户失败
                    reject(error);
                });
        });
        return promise;
    }

    logOut() {
        agconnect.auth().signOut();
        const userStore = userInfoStore()
        userStore.$reset()
    }

    async getCurrectUser() {
        return agconnect.auth().getCurrentUser()
    }
}

export let agcApis: AgcApis = new AgcApis();